import {createRouter, createWebHistory} from "vue-router";
import {routerArray} from "./routers";
import {message} from "ant-design-vue";
import {PagePath, setDocumentTitle} from "@/util/commonUtil";
import {ref} from "vue";
import {useSpinStore} from "@/store/system/spinStore";

export const router = createRouter({
    history: createWebHistory(),
    routes: routerArray,
    strict: true,
    scrollBehavior: () => ({left: 0, top: 0}),
})

const timer = ref<any>(null)
//@ts-ignore
// ----------------------- 前置路由守卫 -----------------------
router.beforeEach(async (to, from, next) => {
    if (isPathInRouterArray(to.path, routerArray) || to.path.includes(PagePath.PostInfoPath) || to.path.includes(PagePath.MedalPath)) {
        if (to?.meta?.title) {
            setDocumentTitle((to.meta.title) as string)
        }
        // 开启加载画面
        useSpinStore().loading = true
        if (timer.value) {
            clearInterval(timer.value)
        }
        next();
    } else {
        message.warning('显然，博主还没有开发适配这个页面！')
        next('/404');
    }
})

router.afterEach(() => {
    // 延时1秒关闭加载画面
    timer.value = setInterval(() => {
        useSpinStore().loading = false
    }, 3500)
})

/**
 * 递归检查给定路径是否存在于路由数组中
 * @param path 要检查的路径字符串
 * @param routesList 包含路由信息的数组
 * @returns 如果找到了匹配的路径，则返回true；否则返回false
 */
function isPathInRouterArray(path: string, routesList: any[]): boolean {
    for (const route of routesList) {
        if (route.path === path) {
            return true;
        }
        if (route.children && route.children.length > 0) {
            if (isPathInRouterArray(path, route.children)) {
                return true;
            }
        }
    }
    return false;
}
